﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace Server
{
    public class CXuLyXML
    {
        #region "Biến"
        private string _pathProduct = "./Data/Product.xml";

        public string PathProduct
        {
            get { return _pathProduct; }
            set { _pathProduct = value; }
        }


        private string _pathAccount = "./Data/Account.xml";

        private string _pathReport = "./Data/Report.xml";

        private int _count_Product;

        public int Count_SanPham
        {
            get
            {
                return LayDanhSachSanPham().Count;
            }
        }

        private int _count_Account;

        public int Count_Account
        {
            get { return LayDanhSachAccount().Count; }
        }
        #endregion

        #region "Phương thức"
        XmlDocument LoadXML(string path)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.PreserveWhitespace = false;
                xmlDoc.XmlResolver = null;
                xmlDoc.Load(path);
                return xmlDoc;
            }
            catch (Exception c)
            {
                throw new Exception(c.Message);
            }
        }
        XmlDocument LoadTextXML(string strXML)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.PreserveWhitespace = false;
                xmlDoc.XmlResolver = null;
                xmlDoc.LoadXml(strXML);
                return xmlDoc;
            }
            catch (Exception c)
            {
                throw new Exception(c.Message);
            }
        }
        /// <summary>
        /// Lấy danh sách sản phẩm
        /// </summary>
        /// <returns></returns>
        public List<CProduct> LayDanhSachSanPham()
        {
            List<CProduct> listproduct = new List<CProduct>();
            XmlDocument xmlDoc = LoadXML(_pathProduct);
            XmlNodeList fullList = xmlDoc.SelectNodes("//sanpham");

            if (fullList.Count != 0)
            {
                foreach (XmlNode node in fullList)
                {
                    try
                    {
                        XmlNodeList childnode = node.ChildNodes;
                        CProduct product = new CProduct(childnode);
                        listproduct.Add(product);
                    }
                    catch (Exception c)
                    {
                        throw new Exception("Định dạng CSDL không đúng");
                    }
                }
                xmlDoc.Save(_pathProduct);
            }
            return listproduct;
        }

        /// <summary>
        /// Lấy danh sách account
        /// </summary>
        /// <returns></returns>
        public List<CAccount> LayDanhSachAccount()
        {
            List<CAccount> listAccount = new List<CAccount>();
            XmlDocument xmlDoc = LoadXML(_pathAccount);

            XmlNodeList fullList = xmlDoc.SelectNodes("//thongtintaikhoan");

            if (fullList.Count != 0)
            {
                foreach (XmlNode node in fullList)
                {
                    try
                    {
                        XmlNodeList childnode = node.ChildNodes;
                        CAccount account = new CAccount(childnode);
                        listAccount.Add(account);
                    }
                    catch (Exception c)
                    {
                        throw new Exception("Định dạng CSDL không đúng");
                    }
                }
            }
            return listAccount;
        }
        /// <summary>
        /// Kiểm tra đăng nhập
        /// </summary>
        /// <param name="user"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        public bool IsDangNhap(string user, string pass)
        {
            XmlDocument xmlDoc = LoadXML(_pathAccount);

            XmlNode node = xmlDoc.SelectSingleNode("//thongtintaikhoan[normalize-space(taikhoan)='" + user + "']/matkhau");

            if (node != null)
            {
                if (node.InnerText.Trim().Equals(pass))
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// Thêm tài khoản
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public bool ThemTaiKhoan(CAccount account)
        {
            if (!KiemTraTaiKhoan_DangKy(account))
            {
                XMLAddNode(account);
                return true;
            }
            return false;
        }
        /// <summary>
        /// Thêm node vào trong XML
        /// </summary>
        /// <param name="account"></param>
        private void XMLAddNode(CAccount account)
        {
            XmlDocument xmlDoc = LoadXML(_pathAccount);
            XmlNode root = xmlDoc.SelectSingleNode("//goc");
            XmlElement nodethongtintaikhoan = xmlDoc.CreateElement("thongtintaikhoan");
            nodethongtintaikhoan.AppendChild(xmlDoc.CreateElement("taikhoan")).InnerText = account.Taikhoan;
            nodethongtintaikhoan.AppendChild(xmlDoc.CreateElement("matkhau")).InnerText = account.Matkhau;
            nodethongtintaikhoan.AppendChild(xmlDoc.CreateElement("truso")).InnerText = account.Truso;
            nodethongtintaikhoan.AppendChild(xmlDoc.CreateElement("diachi")).InnerText = account.Diachi;
            nodethongtintaikhoan.AppendChild(xmlDoc.CreateElement("dienthoai")).InnerText = account.Dienthoai;
            nodethongtintaikhoan.AppendChild(xmlDoc.CreateElement("email")).InnerText = account.Email;

            root.AppendChild(nodethongtintaikhoan);
            xmlDoc.Save(_pathAccount);
        }
        /// <summary>
        /// Kiểm tra tài khoản
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        private bool KiemTraTaiKhoan_DangKy(CAccount account)
        {

            XmlDocument xmlDoc = LoadXML(_pathAccount);

            XmlNode node = xmlDoc.SelectSingleNode
                ("//thongtintaikhoan[normalize-space(taikhoan)='"
                + account.Taikhoan.Trim()
                + "']/*|//thongtintaikhoan[normalize-space(diachi)='"
                + account.Diachi.Trim()
                + "']/*|//thongtintaikhoan[normalize-space(truso)='"
                + account.Truso.Trim()
                + "']/*|//thongtintaikhoan[normalize-space(dienthoai)='"
                + account.Dienthoai.Trim()
                + "']/*|//thongtintaikhoan[normalize-space(email)='"
                + account.Email.Trim()
                + "']/*");
            if (node == null)
                return false;
            return true;
        }
        /// <summary>
        /// Lấy toàn bộ sản phẩm
        /// </summary>
        /// <returns></returns>
        internal string LayToanBoSanpham()
        {
            XmlDocument xmlDoc = LoadXML(_pathProduct);
            string str = xmlDoc.InnerXml.Replace("\r", "").Replace("\t", "").Replace("\n", "").Trim();
            return str;
        }
        /// <summary>
        /// Thống kê báo cáo trong ngày
        /// </summary>
        /// <returns></returns>
        internal string BaoCao_TheoNgay(string _user, string _ngayban)
        {
            string reportxml = string.Empty;

            XmlDocument xmlDoc = LoadXML(_pathReport);
            XmlNodeList node = xmlDoc.SelectNodes
                ("//taikhoan[normalize-space(@key)='"
                + _user
                + "']/thoigian[contains(@value,'"
                + CDateTime.DateTimeParse(_ngayban).ToShortDateString()
                + "')]");

            if (node != null)
            {
                foreach (XmlNode i in node)
                {
                    reportxml += i.OuterXml.Replace("\r", "").Replace("\t", "").Replace("\n", "").Trim();
                }
            }
            else
            {
                reportxml = "Không có thống kê ngày " + _ngayban;
            }

            return reportxml;
        }
        /// <summary>
        /// Lưu thông tin thống kê xuống file report
        /// </summary>
        /// <param name="_user_1"></param>
        /// <param name="_masanpham"></param>
        /// <param name="_tongsoluong"></param>
        /// <param name="_thanhtien"></param>
        /// <param name="_ngayban"></param>
        internal void ThongKeNgay_TuClient(string _user_1, string _masanpham, string _tongsoluong, string _thanhtien, string _ngayban)
        {
            XMLAddNode(_user_1, _masanpham, _tongsoluong, _thanhtien, _ngayban);
        }
        /// <summary>
        /// Thêm báo cáo ngày của Client
        /// </summary>
        /// <param name="_user_1"></param>
        /// <param name="_masanpham"></param>
        /// <param name="_tongsoluong"></param>
        /// <param name="_thanhtien"></param>
        /// <param name="_ngayban"></param>
        private void XMLAddNode(string _user_1, string _masanpham, string _tongsoluong, string _thanhtien, string _ngayban)
        {
            XmlDocument xmlDoc = LoadXML(_pathReport);

            //XmlNodeList root = xmlDoc.SelectNodes
            //    ("//taikhoan[normalize-space(@key)='"
            //    + _user_1
            //    + "']");

            //if (root.Count == 0)//
            //{
            XmlNode root_1 = xmlDoc.SelectSingleNode("//taikhoan[normalize-space(@key)='" + _user_1 + "']");
            if (root_1 == null)//Không tìm thấy tài khoản trong file log
            {
                root_1 = xmlDoc.SelectSingleNode("//goc");
                if (root_1 == null)//Chưa tồn tại nút gốc
                {
                    XmlNode goc = xmlDoc.AppendChild(xmlDoc.CreateElement("goc"));

                    XmlElement taikhoan = xmlDoc.CreateElement("taikhoan");
                    taikhoan.SetAttribute("key", _user_1);

                    XmlElement thoigian = xmlDoc.CreateElement("thoigian");
                    thoigian.SetAttribute("value", CDateTime.DateTimeParse(_ngayban).ToShortDateString());

                    taikhoan.AppendChild(thoigian);

                    thoigian.AppendChild(xmlDoc.CreateElement("sanpham")).InnerText = _masanpham;
                    thoigian.AppendChild(xmlDoc.CreateElement("soluong")).InnerText = _tongsoluong;
                    thoigian.AppendChild(xmlDoc.CreateElement("thanhtien")).InnerText = string.Format("{0:c}", _thanhtien).Replace("$", "").Replace(".00", "");

                    goc.AppendChild(taikhoan);
                    xmlDoc.AppendChild(goc);
                }
                else//Tồn tại gốc trong Report
                {
                    XmlElement taikhoan = xmlDoc.CreateElement("taikhoan");
                    taikhoan.SetAttribute("key", _user_1);

                    XmlElement thoigian = xmlDoc.CreateElement("thoigian");
                    thoigian.SetAttribute("value", CDateTime.DateTimeParse(_ngayban).ToShortDateString());


                    thoigian.AppendChild(xmlDoc.CreateElement("sanpham")).InnerText = _masanpham;
                    thoigian.AppendChild(xmlDoc.CreateElement("soluong")).InnerText = _tongsoluong;
                    thoigian.AppendChild(xmlDoc.CreateElement("thanhtien")).InnerText = string.Format("{0:c}", _thanhtien).Replace("$", "").Replace(".00", "");
                    taikhoan.AppendChild(thoigian);
                    root_1.AppendChild(taikhoan);
                }
            }
            else
            {
                XmlElement thoigian = xmlDoc.CreateElement("thoigian");
                thoigian.SetAttribute("value", CDateTime.DateTimeParse(_ngayban).ToShortDateString());
                XmlNode node_1 = xmlDoc.SelectSingleNode
                                 ("//taikhoan[normalize-space(@key)='"
                                 + _user_1
                                 + "']/thoigian[contains(@value,'"
                                 + DateTime.Parse(_ngayban).ToShortDateString()
                                 + "')][normalize-space(sanpham)="
                                 + _masanpham
                                 + "]");

                if (node_1 == null)
                {
                    thoigian.AppendChild(xmlDoc.CreateElement("sanpham")).InnerText = _masanpham;
                    thoigian.AppendChild(xmlDoc.CreateElement("soluong")).InnerText = _tongsoluong;
                    thoigian.AppendChild(xmlDoc.CreateElement("thanhtien")).InnerText = string.Format("{0:c}", _thanhtien).Replace("$", "").Replace(".00", "");
                    root_1.AppendChild(thoigian);
                }
                else
                {
                    node_1.ChildNodes.Item(0).InnerText = _masanpham;
                    node_1.ChildNodes.Item(1).InnerText = (int.Parse(node_1.ChildNodes.Item(1).InnerText) + int.Parse(_tongsoluong)).ToString();
                    node_1.ChildNodes.Item(2).InnerText = string.Format("{0:c}", double.Parse(node_1.ChildNodes.Item(1).InnerText) + double.Parse(_thanhtien)).Replace("$", "").Replace(".00", "");
                }
            }

            xmlDoc.Save(_pathReport);
        }
        public List<DateTime> LayCacNgayBanHang ()
        {
            List<DateTime> list = new List<DateTime>();
            XmlDocument xml = LoadXML(_pathReport);
            string xpath = "//thoigian";
            XmlNodeList listnode = xml.SelectNodes(xpath);
            if (listnode.Count != 0)
            {
                foreach (XmlNode i in listnode)
                {
                    string _strdate = i.Attributes["value"].InnerText;
                    DateTime _date = CDateTime.DateTimeParse(_strdate);
                    if(!list.Contains(_date))
                        list.Add(_date);
                }
            }
            return list;
        }
        /// <summary>
        /// Cập nhật sản phẩm
        /// </summary>
        /// <param name="producupdate"></param>
        internal void CapNhatSanPham(CProduct producupdate)
        {
            XmlDocument xmlDoc = LoadXML(_pathProduct);

            XmlNode _Node = xmlDoc.SelectSingleNode("//sanpham[normalize-space(ma)=" + producupdate.Ma.ToString() + "]");

            _Node.ChildNodes[1].InnerText = producupdate.Ten;
            _Node.ChildNodes[2].InnerText = string.Format("{0:c}", producupdate.Giatien.ToString()).Replace("$","").Replace(".00","");
            _Node.ChildNodes[3].InnerText = producupdate.Mota;
            _Node.ChildNodes[4].InnerText = producupdate.Ngaydang.ToShortDateString();

            xmlDoc.Save(_pathProduct);
        }
        /// <summary>
        /// Lấy báo cáo chung
        /// </summary>
        /// <param name="_ngaybaocao"></param>
        /// <returns></returns>
        public CReport LayDanhSachBaoCao(DateTime _ngaybaocao)
        {
            CReport _report = new CReport();

            XmlDocument xmlDoc = LoadXML(_pathReport);

            string _ngaybc = _ngaybaocao.ToShortDateString();
            string xpath = "//thoigian[contains(@value, '" + _ngaybc + "')]";

            XmlNodeList node = xmlDoc.SelectNodes(xpath);

            if (node != null)
            {
                XmlDocument xmlProduct = LoadXML(_pathProduct);
                foreach (XmlNode var in node)
                {
                    XmlNode _Node = xmlProduct.SelectSingleNode("//sanpham[normalize-space(ma)=" + var.ChildNodes.Item(0).InnerText.Trim() + "]");

                    if (_Node != null)
                    {
                        try
                        {
                            bool flag = false;
                            foreach (var i in _report.Listsanphamban)
                            {
                                if (i.Ma == int.Parse(var.ChildNodes.Item(0).InnerText.Trim()))
                                {
                                    flag = true;
                                    break;
                                }
                            }
                            if (flag == true)
                            {
                                continue;
                            }
                            xpath = "//thoigian[contains(@value, '" + _ngaybc + "')][normalize-space(sanpham)='" + var.ChildNodes.Item(0).InnerText.Trim() + "']";
                            XmlNodeList tknode = xmlDoc.SelectNodes(xpath);

                            CProduct product = new CProduct(_Node.ChildNodes);
                            if (tknode.Count != 0)
                            {
                                foreach (XmlNode i in tknode)
                                {
                                    product.Soluongbanduoc += int.Parse(var.ChildNodes.Item(1).InnerText.Trim());
                                    product.Doanhthu += double.Parse(var.ChildNodes.Item(2).InnerText.Trim());
                                }
                            }

                            if (product.Soluongbanduoc > _report.Soluongsanphambannhieunhat)
                            {
                                _report.Sanphambannhieunhat = product;
                                _report.Soluongsanphambannhieunhat = product.Soluongbanduoc;
                            }
                            if (product.Soluongbanduoc < _report.Soluongsanphambanitnhat || _report.Soluongsanphambanitnhat == 0)
                            {
                                _report.Sanphambanitnhat = product;
                                _report.Soluongsanphambanitnhat = product.Soluongbanduoc;
                            }
                            _report.Tongdoanhthu += product.Doanhthu;
                            _report.Listsanphamban.Add(product);
                            _report.Ngaybaocao = _ngaybaocao;
                        }
                        catch (Exception c)
                        {
                            throw new Exception("Định dạng CSDL không đúng");
                        }
                    }
                }
                return _report;
            }
            return null;
        }
        /// <summary>
        /// Lấy báo cáo riêng
        /// </summary>
        /// <param name="_ngaybaocao"></param>
        /// <param name="_user"></param>
        /// <returns></returns>
        public CReport LayDanhSachBaoCao(DateTime _ngaybaocao, string _user)
        {
            CReport _report = new CReport();

            XmlDocument xmlDoc = LoadXML(_pathReport);

            string _ngaybc = _ngaybaocao.ToShortDateString();
            string xpath = "//taikhoan[normalize-space(@key)='" + _user + "']/thoigian[contains(@value, '" + _ngaybc + "')]";
            XmlNodeList node = xmlDoc.SelectNodes(xpath);
            if (node.Count != 0)
            {
                XmlDocument xmlProduct = LoadXML(_pathProduct);


                foreach (XmlNode var in node)
                {
                    XmlNode _Node = xmlProduct.SelectSingleNode("//sanpham[normalize-space(ma)=" + var.ChildNodes.Item(0).InnerText.Trim() + "]");
                    if (_Node != null)
                    {
                        try
                        {
                            CProduct product = new CProduct(_Node.ChildNodes);
                            product.Soluongbanduoc = int.Parse(var.ChildNodes.Item(1).InnerText.Trim());
                            product.Doanhthu = double.Parse(var.ChildNodes.Item(2).InnerText.Trim());
                            if (product.Soluongbanduoc > _report.Soluongsanphambannhieunhat)
                            {
                                _report.Sanphambannhieunhat = product;
                                _report.Soluongsanphambannhieunhat = product.Soluongbanduoc;
                            }
                            if (product.Soluongbanduoc < _report.Soluongsanphambanitnhat || _report.Soluongsanphambanitnhat == 0)
                            {
                                _report.Sanphambanitnhat = product;
                                _report.Soluongsanphambanitnhat = product.Soluongbanduoc;
                            }
                            _report.Tongdoanhthu += product.Doanhthu;
                            _report.Listsanphamban.Add(product);
                            _report.Ngaybaocao = _ngaybaocao;
                        }
                        catch (Exception c)
                        {
                            throw new Exception("Định dạng CSDL không đúng");
                        }
                    }
                }
                return _report;
            }
            return null;

        }
        #endregion

        #region "Sự kiện"

        #endregion


    }
}
